const crypto = require('crypto')
const tencentcloud = require("tencentcloud-sdk-nodejs");
const VodClient = tencentcloud.vod.v20180717.Client;
import { secretId,secretKey, video_SubAppId } from "src/setting";
import { appendFileSync, writeFileSync } from "fs";
import { join } from "path";
import axios from 'axios'
import { Redis } from "ioredis";


const clientConfig = {
  credential: {
    secretId: secretId,
    secretKey: secretKey,
  },
  region: "",
  profile: {
    httpProfile: {
      endpoint: "vod.tencentcloudapi.com",
    },
  },
};
const video_RefererKey = process.env.cloudrefererkey || 'oSbCoMKOQO5LQcyWjglw'
const video_VideoTimeout = 60 * 120
const SubAppId = 1500023094

class utils {
  constructor(){

  }
  user_token_key = '5KdQqxSw8NC5tC8na641yjDN8s6t2KLxtWJuoA5pijthS8jnmE3'
  redis_withdrawal_key = "payconsumption:withdrawal:";
  redis_payconsumption_key = "payconsumption:wallet:";

  async getAccessToken(redis: Redis, cb){
    let checkdirtydatarobot = await redis.get('checkdirtydatarobot')
    if(checkdirtydatarobot){
      return cb(checkdirtydatarobot)
    }
    axios.get('https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwce709c41419a5598&corpsecret=W8zeaho-_0UPG_GVVCab1y_XN0JCsCaEBQhHDG8sYAo').then(async res => {
      console.log(res.data,'res')
      if(res.data && res.data.errcode == 0){
        // redis.set('checkdirtydatarobot', res.data.access_token)
        await redis.setex('checkdirtydatarobot', Number(res.data.expires_in), res.data.access_token)
        cb(res.data.access_token)
      }
    })
  }

  send_to_qw(redis: Redis, message: string){
    this.getAccessToken(redis, (access_token) => {
      console.log(message,'message')
      let headers = {
        "Content-Type": "application/json"
      }
      let data = {
          "touser" : "zhangqiang",
          "toparty" : "",
          "totag" : "",
          "msgtype" : "text",
          "agentid" : 1000004,
          "text" : {
            "content" : `[${process.env.ServerApp || 'uat'}]${message}`
          },
          "safe":0,
          "enable_id_trans": 0,
          "enable_duplicate_check": 0,
          "duplicate_check_interval": 1800
      }
      axios.post("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + access_token,data, {
        headers: headers,
      }).then(res => {
        // console.log(res,'ress')
      }).catch(err => {
        console.log(err,'error')
      })
    })

    // Logger.log("send to qw")
    // res = requests.post("https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=294c178b-0e91-4654-84a5-4404eac7b6c6", headers=headers, data=json.dumps(data))
    // Logger.log(res.text)
  }

  md5(content) {
    const md5 = crypto.createHash('md5')
    return md5.update(content).digest('hex')
  }

  /**
   * 获取防盗链视频链接
   * @param currentVideo
   */
   getPlayVideoUrl(video_url){
    let oldurl:any = video_url || ''
    let https = 'https://'
    let http = 'http://'
    if(oldurl.indexOf(https) > -1){
      oldurl = oldurl.substring(oldurl.indexOf(https) + https.length)
    }else if(oldurl.indexOf(http) > -1){
      oldurl = oldurl.substring(oldurl.indexOf(http) + http.length)
    }
    oldurl = oldurl.split('/')
    oldurl = oldurl.slice(1,oldurl.length - 1)
    let endTime:string = parseInt((new Date().getTime() / 1000 + video_VideoTimeout).toString()).toString(16)
    let sign = this.md5(video_RefererKey + '/' + oldurl.join('/') + '/' + endTime)
    if(video_url){
      let newurl = video_url + '?t=' + endTime + '&sign=' + sign
      video_url = newurl
    }
    return video_url
  }

  DeleteMedia(FileId) {
    const client = new VodClient(clientConfig);
    return client.DeleteMedia({
      SubAppId: SubAppId,
      FileId:FileId
    })
  }

  SearchMedia(ClassIds: number[]){
    const client = new VodClient(clientConfig);
    return client.SearchMedia({
      SubAppId: video_SubAppId,
      ClassIds:ClassIds,
      Offset: 0,
      Limit: 5000
    })
  }

  /**
   * 查询腾讯云点播执行
   * @param client 
   * @param TaskId 
   * @param SubAppId 
   */
   DescribeTaskDetail(client, TaskId: string, cb?: Function){
    client.DescribeTaskDetail({TaskId:TaskId, SubAppId: SubAppId}).then(async(res) => {
      if(res.Status === 'FINISH'){
        console.log(res,'res')
        let video_id_new = ''
        let video_url_new = ''
        let video_cover_new = ''
        if(res.TaskType == 'PullUpload'){
          let PullUploadTask = res.PullUploadTask
          video_id_new = PullUploadTask.FileId
          video_url_new = PullUploadTask.MediaBasicInfo.MediaUrl
          video_cover_new = PullUploadTask.MediaBasicInfo.CoverUrl

          if(PullUploadTask.Status == 'FINISH'){
            cb({video_id_new, video_url_new, video_cover_new})
            return
          }
        }
      }
      setTimeout(() => {
        this.DescribeTaskDetail(client, TaskId, cb)
      },1000)
    }).catch(err => {
      cb && cb(err)
      // resolve(data)
    })
  }

  pullMediaAndUpload(FileId: string, mediaUrl: string, coverUrl: string, video_id: number, videoType: string){
    const client = new VodClient(clientConfig);
    const params:any = {
      "CoverUrl": coverUrl,
      "SubAppId": SubAppId,
      "MediaName": video_id + '_' + FileId + videoType
    };
    if(mediaUrl){
      params.MediaUrl = this.getPlayVideoUrl(mediaUrl)
    }else{
      params.MediaUrl = coverUrl
    }
    if(!coverUrl){
      delete params.CoverUrl
    }
    console.log(params,'params')
    return new Promise(async (resolve,reject) => {
      client.PullUpload(params).then(
        (data) => {
          this.DescribeTaskDetail(client, data.TaskId, (result) => {
            resolve(result)
          })
        },
        (err) => {
          reject(err)
        }
      );
    })
  }
  

  /**
   * 获取limit
   * @param pageSize 
   * @param pageIndex 
   * @returns 
   */
  getLimit(pageSize: number, pageIndex: number){
    pageSize = Number(pageSize) || 0
    pageIndex = Number(pageIndex) || 0
    let skip: number = pageSize * pageIndex
    return {skip, take: pageSize}
  }

  
  /**
   * 生成随机字符串
   */
   randomString(len: number) {
    len = len || 32;
    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var maxPos = $chars.length;
    var pwd = '';
    for (var i = 0; i < len; i++) {
      pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
  }

  guid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
      return v.toString(16);
    });
  }

  
  Format(time, fmt) {
    //author: meizz
    var o = {
      'M+': time.getMonth() + 1, //月份
      'd+': time.getDate(), //日
      'h+': time.getHours(), //小时
      'm+': time.getMinutes(), //分
      's+': time.getSeconds(), //秒
      'q+': Math.floor((time.getMonth() + 3) / 3), //季度
      S: time.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (time.getFullYear() + '').substr(4 - RegExp.$1.length));
    for (var k in o)
      if (new RegExp('(' + k + ')').test(fmt)){
        if(k === 'S'){
          fmt = fmt.replace(RegExp.$1, ('000' + o[k]).substr(('' + o[k]).length));
        }else{
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
        }
      }
    return fmt;
  };

  randomStringID(len_str: number, len_number: number, str_first?: boolean){
    len_str = len_str || 1;
    len_number = len_number || 5;
    var $chars = 'ABCDEFGHJKLMNPQRSTWXYZ';
    var $chars_number = '0123456789'
    var maxPos = $chars.length;
    var maxPos_number = $chars_number.length;
    var pwd = '';
    if(str_first){
      for (var i = 0; i < len_str; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
      }
      for (var i = 0; i < len_number; i++) {
        pwd += $chars_number.charAt(Math.floor(Math.random() * maxPos_number));
      }
    }else{
      for (var i = 0; i < len_number; i++) {
        pwd += $chars_number.charAt(Math.floor(Math.random() * maxPos_number));
      }
      for (var i = 0; i < len_str; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
      }
    }
    return pwd;
  }

  isJSON(txt){
    try{
      if(!(txt||'').trim()){
        return false
      }
      let data = JSON.parse(txt)
      return true
    }catch(err){
      return false
    }
  }
  
}

export default new utils()
